<?php
/**
 * Created by PhpStorm.
 * User: wbj08
 * Date: 2019/2/15
 * Time: 14:59
 */
defined('IN_IA') or exit('Access Denied');

class DgjyModuleWxapp extends WeModuleWxapp {

    public function doPageUpdateUserInfo() {
        global $_GPC, $_W;
        $uid      = $_GPC['uid'];
        $fans     = pdo_get('mc_mapping_fans', array('uid' => $uid));
        $openid   = $fans['openid'];
        $userinfo = pdo_get('dgjy_user', array('uid' => $uid));

        if ($userinfo) {
            $updatedata = array(
                'openid'     => $openid,
                'nickname'   => $_GPC['nickName'],
                'avatar'     => $_GPC['avatarUrl'],
                'city'       => $_GPC['city'],
                'province'   => $_GPC['province'],
                'country'    => $_GPC['country'],
                'login_time' => TIMESTAMP,
            );

            $id = pdo_update('dgjy_user', $updatedata, array('uid' => $uid));
        } else {
            $insertdata = array(
                'uniacid'    => $_W['uniacid'],
                'openid'     => $openid,
                'uid'        => $_GPC['uid'],
                'nickname'   => $_GPC['nickName'],
                'avatar'     => $_GPC['avatarUrl'],
                'city'       => $_GPC['city'],
                'province'   => $_GPC['province'],
                'country'    => $_GPC['country'],
                'createtime' => TIMESTAMP,
            );
            pdo_insert('dgjy_user', $insertdata);
            $id = pdo_insertid();
        }

        $userinfo = pdo_get('dgjy_user', array('uid' => $uid));

        if ($id) {
            $list = array('msg' => '提交成功', 'error' => 0, 'userInfo' => $userinfo);
        } else {
            $list = array('msg' => '提交失败', 'error' => 1);
        }

        return $this->result(0, 'success', $list);
    }

    public function doPageUpdateUserReal() {
        global $_GPC, $_W;
        $uid = $_GPC['uid'];

        $updatedata = array(
            'realname' => $_GPC['realname'],
            'phone'    => $_GPC['phone'],
        );

        $id = pdo_update('dgjy_user', $updatedata, array('uid' => $uid));

        $userinfo = pdo_get('dgjy_user', array('uid' => $uid));

        if ($id) {
            $list = array('msg' => '保存成功', 'error' => 0, 'userInfo' => $userinfo);
            return $this->result(0, 'success', $list);
        } else {
            return $this->result(1, '保存失败');
        }

    }

    public function doPageBanners() {
        global $_GPC, $_W;
        $type = $_GPC['btype'];

        $query  = load()->object('query');
        $banner = $query->from('dgjy_banner')->where('uniacid', $_W['uniacid'])->where('ads_type', $type)->orderby('ads_id', 'ASC')->getall();//banner列表
        foreach ($banner as $key => $value) {
            if (!empty($value['ads_pic'])) {
                $banner[$key]['ads_pic'] = $_W['attachurl'] . $value['ads_pic'];
            }
        }
        return $this->result(0, 'success', $banner);
    }

    public function doPageCategory() {
        $query     = load()->object('query');
        $categorys = $query->from('dgjy_article_category')->getall();//动态列表的分类
        return $this->result(0, 'success', $categorys);
    }

    public function doPageNewsList() {
        global $_GPC, $_W;
        $cateid = intval($_GPC['cateid']);

        $pageIndex = max(1, intval($_GPC['page']));
        if (!empty(intval($_GPC['pageSize']))) {
            $pageSize = $_GPC['pageSize'];
        } else {
            $pageSize = 10;
        }

//        $list = array('$cateid' => $cateid, '$pageIndex' => $pageIndex, '$pageSize' => $pageSize);
//        return $this->result(0, 'success', $list);

        $query = load()->object('query');
        $newsT = $query->from('dgjy_article_news');
        if (!empty($cateid)) {
            if ($cateid == -1) {//推荐信息
                $newsT = $newsT->where('is_show_home', 1);
            } elseif ($cateid == -2) {//最新公告
            } else {
                $newsT = $newsT->where('cateid', $cateid)->orderby('is_show_home', 'DESC');

            }
        }

        $news = $newsT->orderby('createtime', 'DESC')->limit(($pageIndex - 1) * $pageSize, $pageSize)->getall();//新闻列表
        foreach ($news as $key => $value) {
            if (!empty($value['thumb'])) {
                $news[$key]['thumb'] = $_W['attachurl'] . $value['thumb'];
            }
        }

        return $this->result(0, 'success', $news);
    }

    public function doPageNewsDetail() {
        global $_GPC, $_W;
        $newsId = $_GPC['newsId'];

        $query  = load()->object('query');
        $detail = $query->from('dgjy_article_news')->where('id', $newsId)->get();//新闻详情

//        $list = array('$newsId' => $newsId, '$detail' => $detail);
//        return $this->result(0, 'success', $list);
        if (!empty($detail['thumb'])) {
            $detail['thumb'] = $_W['attachurl'] . $detail['thumb'];
        }
        return $this->result(0, 'success', $detail);
    }

    public function doPageTalkAdd() {
        global $_GPC, $_W;
        $uid        = $_GPC['uid'];
        $fans       = pdo_get('mc_mapping_fans', array('uid' => $uid));
        $openid     = $fans['openid'];
        $title      = $_GPC['title'];
        $content    = $_GPC['content'];
        $pictureUrl = $_GPC['images'];
        $picture    = explode(',', $pictureUrl);
//        if (empty($picture)) {
//            $list = array('$picture图片空' => $picture, 'error' => 0);
//            return $this->result(0, 'success', $list);
//        }else{
//            $list = array('$picture' => $picture, 'error' => 0);
//            return $this->result(0, 'success', $list);
//        }

        $data = array(
            'openid'       => $openid,
            'uniacid'      => $_W['uniacid'],
            'talk_pid'     => "4",
            'talk_type'    => "2",//普通用户发的
            'talk_did'     => "1",
            'talk_title'   => $title,
            'talk_content' => $content,
            'talk_time'    => TIMESTAMP,
            'talk_pic'     => $pictureUrl,
        );
        $res  = pdo_insert('dgjy_talk', $data);
        if (!empty($res)) {
            if (empty($picture)) {//没图片,直接添加完成
                $list = array('msg' => '发布成功无图片', 'error' => 0);
            } else {
                $vid = pdo_insertId();//新建话题
                $res = 0;
                //上传图片开始
                foreach ($picture as $key => $v) {
                    $picdata = array(
                        'uniacid'      => $_W['uniacid'],
                        'picture_pid'  => '1',
                        'picture_type' => 'talk',
                        'picture_vid'  => $vid,
                        'picture_show' => '1',
                        'openid'       => $openid,
                        'picture_url'  => $v,
                        'picture_time' => TIMESTAMP,
                    );

                    $res += pdo_insert('dgjy_picture', $picdata);

                }
                //上传图片结束
                if (empty($res)) {
                    $list = array('msg' => '图片保存失败', 'error' => 0);
                } else {
                    $list = array('msg' => '发布成功带图片', 'error' => 0);
                }
                return $this->result(0, 'success', $list);
            }
        } else {
            $list = array('msg' => '提交失败', 'error' => 1);
        }
        return $this->result(0, 'success', $list);
    }

    public function doPageTalkList() {
        global $_GPC, $_W;
        $openid = $_GPC['openid'];
        $type   = intval($_GPC['type']);
        $type   = !empty($type) ? $type : 0;

        $pageIndex = max(1, intval($_GPC['page']));
        if (!empty(intval($_GPC['pageSize']))) {
            $pageSize = $_GPC['pageSize'];
        } else {
            $pageSize = 10;
        }

//        $list = array('type' => $type, '$pageIndex' => $pageIndex, '$pageSize' => $pageSize);
//        return $this->result(0, 'success', $list);

        $query = load()->object('query');
        $talkT = $query->from('dgjy_talk');
        switch ($type) {
            case 0:
                $talkT = $talkT->where('talk_type', 2)->orderby('talk_time', 'DESC');//talk_type为2 则为用户话题,根据最新发布时间排序
                break;
            case 1:
                $talkT = $talkT->where('talk_type', 2)->orderby('talk_view', 'DESC');//根据浏览量排序
                break;
            case 2:
                $talkT = $talkT->where('talk_type', 1)->orderby('talk_did', 'DESC')->orderby('talk_time', "DESC");//talk_type为1 则为官方话题
                break;
            case 3:
                $talkT = $talkT->where('talk_type', 1)->orderby('talk_did', 'DESC')->orderby('talk_time', "DESC");//talk_type为1 则为官方话题
                break;
        }

        $talks = $talkT->limit(($pageIndex - 1) * $pageSize, $pageSize)->getall();//话题列表
        $talks = $this->fillTalks($talks, $openid);

        return $this->result(0, 'success', $talks);
    }

    private function fillTalks($talks, $openid) {
        global $_W;
        $query = load()->object('query');
        //获取每个话题的图片 TODO 暂时不在列表显示图片
//        foreach ($talks as $key => $value) {
//            $picture = $query->from('dgjy_picture')->where('uniacid', $_W['uniacid'])->where('picture_vid', $value['talk_id'])->where('picture_type', 'talk')->where('picture_pid', '1')->getall();
//            $temp    = array();
//            foreach ($picture as $p) {
//                $temp[] = $_W['attachurl'] . $p['picture_url'];
//            }
//            $talks[$key]['images'] = $temp;
//        }
        foreach ($talks as $key => $value) {
            //获取每个话题的赞
//            $oldZan = pdo_fetch("SELECT * FROM" . tablename('dgjy_zan') . "WHERE uniacid=:uniacid AND zan_vid=:zan_vid AND openid=:openid", array(':uniacid' => $_W['uniacid'], ':zan_vid' => $value['talk_id'], 'openid' => $openid));
            $oldZan = $query->from('dgjy_zan')->where('uniacid', $_W['uniacid'])->where('zan_vid', $value['talk_id'])->where('openid', $openid)->get();
            $zan    = $query->from('dgjy_zan')->where('uniacid', $_W['uniacid'])->where('zan_vid', $value['talk_id'])->getall();

            $talks[$key]['zanType']  = empty($oldZan) ? 1 : 2;//没有赞 1, 有赞 2
            $talks[$key]['zanCount'] = count($zan);

            //获取所有评论的数量
            $pinglun = $query->from('dgjy_pinglun')->where('uniacid', $_W['uniacid'])->where('pinglun_vid', $value['talk_id'])->orderby('pinglun_time', 'DESC')->getall();//查询所有评论

            $talks[$key]['commentCount'] = count($pinglun);

            //获取每个话题的用户信息
            $userinfo = pdo_get('dgjy_user', array('openid' => $value['openid']));

            $talks[$key]['user_avatar']   = $userinfo['avatar'];
            $talks[$key]['user_nickname'] = $userinfo['nickname'];
            $talks[$key]['createtime']    = $this->getgaptime($value['talk_time']);
        }
        return $talks;
    }

    public function doPageTalkDetail() {
        global $_GPC, $_W;
        $openid = $_GPC['openid'];
        $talkId = $_GPC['talkId'];

        $query    = load()->object('query');
        $detail   = $query->from('dgjy_talk')->where('talk_id', $talkId)->get();//新闻详情
        $userinfo = $query->from('dgjy_user')->where('openid', $detail['openid'])->get();//获取用户相关信息
        //获取发布的图片
        $picture = $query->from('dgjy_picture')->where('uniacid', $_W['uniacid'])->where('picture_vid', $detail['talk_id'])->where('picture_type', 'talk')->where('picture_pid', '1')->getall();
        $temp    = array();
        foreach ($picture as $p) {
            $temp[] = $_W['attachurl'] . $p['picture_url'];
        }

        $detail['user_avatar']   = $userinfo['avatar'];
        $detail['user_nickname'] = $userinfo['nickname'];
        $detail['createtime']    = $this->getgaptime($detail['talk_time']);
        $detail['pictures']      = $temp;

        //查询赞
        $oldZan = $query->from('dgjy_zan')->where('uniacid', $_W['uniacid'])->where('zan_vid', $talkId)->where('openid', $openid)->get();
        $zan    = $query->from('dgjy_zan')->where('uniacid', $_W['uniacid'])->where('zan_vid', $talkId)->getall();

        $detail['zanType']  = empty($oldZan) ? 1 : 2;//没有赞 1, 有赞 2
        $detail['zanCount'] = count($zan);

        //查询评论
        $pinglun = $query->from('dgjy_pinglun')->where('uniacid', $_W['uniacid'])->where('pinglun_vid', $talkId)->orderby('pinglun_time', 'DESC')->getall();//查询所有评论
        foreach ($pinglun as $key => $value) {
            //获取每个话题的用户信息
            $userinfo = pdo_get('dgjy_user', array('openid' => $value['openid']));

            $pinglun[$key]['user_avatar']   = $userinfo['avatar'];
            $pinglun[$key]['user_nickname'] = $userinfo['nickname'];
            $pinglun[$key]['createtime']    = $this->getgaptime($value['pinglun_time']);
        }
        $detail['comments'] = $pinglun;

//        $list = array('$talkId' => $talkId, '$detail' => $pinglun);
//        return $this->result(0, 'success', $list);

        if (!empty($detail['teacher_avatar'])) {
            $detail['teacher_avatar'] = $_W['attachurl'] . $detail['teacher_avatar'];
        }
        return $this->result(0, 'success', $detail);
    }

    public function doPageTalkZan() {
        global $_GPC, $_W;
        $openid = $_GPC['openid'];
        $talkId = $_GPC['talkId'];

        $query  = load()->object('query');
        $oldZan = $query->from('dgjy_zan')->where('uniacid', $_W['uniacid'])->where('zan_vid', $talkId)->where('openid', $openid)->get();
        if (empty($oldZan)) {//没有赞
            $zandata = array(
                'uniacid'  => $_W['uniacid'],
                'openid'   => $openid,
                'zan_vid'  => $talkId,
                'zan_time' => TIMESTAMP,
            );

            $res = pdo_insert('dgjy_zan', $zandata);
            $zan = $query->from('dgjy_zan')->where('uniacid', $_W['uniacid'])->where('zan_vid', $talkId)->count();

            $data = array(
                'zanType'  => '2',//点赞
                'zanCount' => $zan,
            );
        } else {
            pdo_delete('dgjy_zan', array('uniacid' => $_W['uniacid'], 'zan_vid' => $talkId, 'openid' => $openid));
            $zan  = $query->from('dgjy_zan')->where('uniacid', $_W['uniacid'])->where('zan_vid', $talkId)->count();
            $data = array(
                'zanType'  => '1',//取消赞,没有赞了
                'zanCount' => $zan,
            );
        }

        return $this->result(0, 'success', $data);
    }

    public function doPageTalkPinglun() {
        global $_GPC, $_W;
        $openid  = $_GPC['openid'];
        $talkId  = $_GPC['talkId'];
        $comment = $_GPC['comment'];

//        $list = array('$talkId' => $talkId, '$comment' => $comment, '$openid' => $openid);
//        return $this->result(0, 'success', $list);

        if (!empty($comment)) {//评论内容不为空
            $newpinglun = array(
                'uniacid'         => $_W['uniacid'],
                'openid'          => $openid,
                'pinglun_vid'     => $talkId,
                'pinglun_content' => $comment,
                'pinglun_time'    => TIMESTAMP,
            );

            $res = pdo_insert('dgjy_pinglun', $newpinglun);
            if (!empty($res)) {
                $pinglunid = pdo_insertId();
                $query     = load()->object('query');
                $userinfo  = pdo_get('dgjy_user', array('openid' => $openid));
                $pinglun   = $query->from('dgjy_pinglun')->where('pinglun_id', $pinglunid)->get();//评论

                $pinglun['user_avatar']   = $userinfo['avatar'];
                $pinglun['user_nickname'] = $userinfo['nickname'];
                $pinglun['createtime']    = '刚刚';

                return $this->result(0, 'success', $pinglun);
            } else {
                return $this->result(1, '评论失败');
            }
        } else {
            return $this->result(1, '请输入评论内容');
        }
    }

    public function doPageTeacherList() {
        global $_GPC, $_W;

        $type = intval($_GPC['type']);
        $type = !empty($type) ? $type : 0;

        $orderType = intval($_GPC['order']);
        $orderType = !empty($orderType) ? $orderType : 0;

//        $list = array('type' => $type, '$pageIndex' => $pageIndex, '$pageSize' => $pageSize);
//        return $this->result(0, 'success', $list);

        $query    = load()->object('query');
        $teacherT = $query->from('dgjy_teacher');
        switch ($type) {
            case 0:
                break;
            case 1:
                $teacherT = $teacherT->where('teacher_type', 1);//业务老师
                break;
            case 2:
                $teacherT = $teacherT->where('teacher_type', 2);//咨询老师
                break;
        }

        switch ($orderType) {
            case 0:
                $teacherT = $teacherT->orderby('app_num', 'DESC');//报名人数排名
                break;
            case 1:
                $teacherT = $teacherT->orderby('teacher_id', 'DESC');//默认排名
                break;
        }

        $teacher = $teacherT->getall();//话题列表
        foreach ($teacher as $key => $value) {
            if (!empty($value['teacher_avatar'])) {
                $teacher[$key]['teacher_avatar'] = $_W['attachurl'] . $value['teacher_avatar'];
            }
        }

        return $this->result(0, 'success', $teacher);
    }

    public function doPageTeacherDetail() {
        global $_GPC, $_W;
        $teacherId = $_GPC['teacherId'];

        $query  = load()->object('query');
        $detail = $query->from('dgjy_teacher')->where('teacher_id', $teacherId)->get();//新闻详情

//        $list = array('$teacherId' => $teacherId, '$detail' => $detail);
//        return $this->result(0, 'success', $list);

        if (!empty($detail['teacher_avatar'])) {
            $detail['teacher_avatar'] = $_W['attachurl'] . $detail['teacher_avatar'];
        }
        return $this->result(0, 'success', $detail);
    }

    public function doPageAppointmentAdd() {
        global $_GPC, $_W;
        $uid         = $_GPC['uid'];
        $fans        = pdo_get('mc_mapping_fans', array('uid' => $uid));
        $openid      = $fans['openid'];
        $teacherId   = $_GPC['teacherId'];
        $stuName     = $_GPC['stuName'];
        $stuPhone    = $_GPC['stuPhone'];
        $appointDate = $_GPC['appointDate'];
        $stuDemand   = $_GPC['stuDemand'];

        $isAppoint = pdo_get('dgjy_appoint', array('openid' => $openid, 'teacher_id' => $teacherId));
        if ($isAppoint) {//已报名了
            return $this->result(1, '您已报名该老师');
        }

        $data = array(
            'openid'       => $openid,
            'uniacid'      => $_W['uniacid'],
            'appoint_pid'  => "1",
            'teacher_id'   => $teacherId,//老师id
            'stu_name'     => $stuName,//学生姓名
            'stu_phone'    => $stuPhone,//学生电话
            'stu_demand'   => $stuDemand,//学生需求
            'appoint_time' => $appointDate,//学生报名日期
            'createtime'   => TIMESTAMP,//创建日期
        );
        $res  = pdo_insert('dgjy_appoint', $data);
        if (!empty($res)) {
            $list = array('msg' => '报名成功', 'error' => 0);
        } else {
            $list = array('msg' => '报名失败', 'error' => 1);
        }
        return $this->result(0, 'success', $list);
    }

    public function doPageSearch() {
        global $_GPC, $_W;
        $openid     = $_GPC['openid'];
        $keyword    = $_GPC['keyword'];
        $searchType = $_GPC['searchType'];

//        $list = array('$keyword' => $keyword, '$searchType' => $searchType);
//        return $this->result(0, 'success', $list);

        $pageIndex = max(1, intval($_GPC['page']));
        if (!empty(intval($_GPC['pageSize']))) {
            $pageSize = $_GPC['pageSize'];
        } else {
            $pageSize = 10;
        }
        $query = load()->object('query');
        switch ($searchType) {
            case 1://搜索新闻
                $sql = "SELECT * FROM " . tablename('dgjy_article_news')
                    . " WHERE title like '%" . $keyword . "%' "
                    . " ORDER BY createtime desc "
                    . " LIMIT " . ($pageIndex - 1) * $pageSize . "," . $pageSize;
//                $news = pdo_fetchall($sql);

                $news = $query->from('dgjy_article_news')->where('title LIKE', "%{$keyword}%")
                    ->orderby('createtime', 'DESC')->limit(($pageIndex - 1) * $pageSize, $pageSize)->getall();

                foreach ($news as $key => $value) {
                    if (!empty($value['thumb'])) {
                        $news[$key]['thumb'] = $_W['attachurl'] . $value['thumb'];
                    }
                }

                return $this->result(0, 'success', $news);
                break;
            case 2://搜索话题
                $talks = $query->from('dgjy_talk')->where('talk_content LIKE', "%{$keyword}%")
                    ->orderby('talk_time', 'DESC')->limit(($pageIndex - 1) * $pageSize, $pageSize)->getall();//话题列表
                $talks = $this->fillTalks($talks, $openid);

                return $this->result(0, 'success', $talks);
                break;
            case 3://搜索老师
                $teacher = $query->from('dgjy_teacher')->where('teacher_name LIKE', "%{$keyword}%")
                    ->orderby('createtime', 'DESC')->limit(($pageIndex - 1) * $pageSize, $pageSize)->getall();//话题列表
                foreach ($teacher as $key => $value) {
                    if (!empty($value['teacher_avatar'])) {
                        $teacher[$key]['teacher_avatar'] = $_W['attachurl'] . $value['teacher_avatar'];
                    }
                }
                return $this->result(0, 'success', $teacher);
                break;
            default:
                return $this->result(1, '请求错误');
        }

    }

    private function getgaptime($oldtime) {
        $gaptime = TIMESTAMP - $oldtime;
        switch ($gaptime) {
            case $gaptime == 0:
                $restime = '刚刚';
                break;
            case $gaptime < 60:
                $restime = $gaptime . '秒之前';
                break;
            case $gaptime < 60 * 60:
                $restime = floor($gaptime / 60) . '分钟前';
                break;
            case $gaptime < 60 * 60 * 24:
                $restime = floor($gaptime / (60 * 60)) . '小时前';
                break;
            case $gaptime < 60 * 60 * 24 * 3;
                $restime = floor($gaptime / (60 * 60 * 24)) == 1 ? '昨天' . date('H:i', $oldtime) : '前天' . date('H:i', $oldtime);
                break;
            case $gaptime < 60 * 60 * 24 * 30:
                $restime = floor($gaptime / (60 * 60 * 24)) . '天前';
                break;
            case $gaptime < 60 * 60 * 24 * 365:
                $restime = floor($gaptime / (60 * 60 * 24 * 30)) . '月前';
                break;
            case $gaptime < 60 * 60 * 24 * 365 * 3:
                $restime = floor($gaptime / (60 * 60 * 24 * 365)) . '年前';
                break;
            default:
                $restime = date('Y-m-d', $oldtime);
        }
        return $restime;
    }

}